package it.softphone.commons.service.security;

import java.io.IOException;
import java.security.GeneralSecurityException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import static it.softphone.commons.util.LogUtil.logger;

public class SecurityServletFilter implements Filter {

	Filter service;
	

	public void destroy() {
		if( service==null ) {
			logger.warn("SecurityAccountService is not initialized!");
			return;
		}
		
		service.destroy();
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		if( service==null ) {
			logger.warn("SecurityAccountService is not initialized!");
			return;
		}
		
		service.doFilter(request, response, chain);
	}

	public void init(FilterConfig filterConfig) throws ServletException {

		try {
			SecurityAccountService sas = SecurityAccountServiceFactory.getSecurityAccountServiceFactory().newSecurityAccountService(null);
			
			if( sas instanceof Filter ) {
				service = (Filter) sas;
				
				service.init(filterConfig);
			}
			else {
				logger.error("SecurityAccountService doesn't implement the javax.servlet.Filter interface");
			}
			
		} catch (GeneralSecurityException e) {
			logger.error("error initializing SecurityAccountService" , e);
			throw new ServletException(e);
		}
		
		
	}

}
